package com.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.common.Result;
import com.springboot.dto.ProductManageDTO;
import com.springboot.entity.Product;
import com.springboot.entity.ProductSku;
import com.springboot.entity.ProductSpecColor;
import com.springboot.entity.ProductSpecSize;
import com.springboot.mapper.ProductMapper;
import com.springboot.mapper.CategoryMapper;
import com.springboot.mapper.ProductSpecColorMapper;
import com.springboot.mapper.ProductSpecSizeMapper;

import com.springboot.service.ICategoryService;
import com.springboot.service.IProductService;
import com.springboot.service.IProductSkuService;
import com.springboot.service.IProductSpecColorService;
import com.springboot.service.IProductSpecSizeService;

import com.springboot.utils.IntegerUtils;
import com.springboot.vo.ProductDetailVO;
import com.springboot.vo.ProductWithCategoryVO;
import com.springboot.vo.ProductSKUVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ICategoryService categoryService;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private IProductSkuService productSkuService;
    @Resource
    private IProductSpecColorService productSpecColorService;
    @Resource
    private IProductSpecSizeService productSpecSizeService;
    @Resource
    private ProductSpecColorMapper productSpecColorMapper;
    @Resource
    private ProductSpecSizeMapper productSpecSizeMapper;

    /**
     * 分页查询所有上架商品（带分类名称）
     *
     * @param pageNum    页码
     * @param pageSize   每页数量
     * @param categoryId 分类id（非叶子分类将会查询所有子叶分类的商品）
     * @param search     搜索参数（商品名）
     * @return 商品分页数据（含分类名称）
     */
    @Override
    public Result getAllOnShelfWithCategoryPage(Integer pageNum, Integer pageSize,Integer status, Integer categoryId, String search, Integer newProduct) {
        IPage<ProductWithCategoryVO> page = new Page<>(pageNum, pageSize);
        if (categoryId != null) {
            if (categoryService.getById(categoryId) == null) {
                return Result.error("此分类不存在");
            }

        }
        List<Integer> categoryIds = categoryId != null ? categoryMapper.selectCategoryIdsByIdRecursive(categoryId) : null;
        IPage<ProductWithCategoryVO> productPage = productMapper.selectAllOnShelfWithCategoryPage(page,status, categoryId, search, newProduct, categoryIds);
        return Result.success(productPage, "查询成功");
    }

    /**
     * 根据商品ID查询商品详情
     *
     * @param productId 商品ID
     * @return 商品详情
     */
    @Override
    public Result getProductDetailById(Integer productId) {
        ProductDetailVO productDetail = productMapper.selectProductDetailById(productId);
        if (productDetail == null) {
            return Result.error("商品不存在");
        }

        // 直接返回原始 specColor/specSize，不再转换为名称
        return Result.success(productDetail, "查询成功");
    }

    /**
     * 新增商品（包括颜色、尺寸和SKU）
     *
     * @param productManageDTO 商品管理DTO
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result addProduct(ProductManageDTO productManageDTO) {
        // 保存商品基本信息
        Product product = new Product();
        product.setProductName(productManageDTO.getProductName());
        product.setCategoryId(productManageDTO.getCategoryId());
        product.setDefaultPrice(productManageDTO.getDefaultPrice());
        product.setMainImage(productManageDTO.getMainImage());
        product.setSubImages(productManageDTO.getSubImages());
        product.setDetail(productManageDTO.getDetail());
        product.setStatus(0); // 默认下架
        product.setNewProduct(0); // 默认非新品
        product.setSales(0); // 默认销量为0
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());

        this.save(product);

        // 建立索引→颜色ID/尺码ID 映射
        Map<Integer, Integer> colorIndexToId = new java.util.HashMap<>();
        Map<Integer, Integer> sizeIndexToId = new java.util.HashMap<>();

        if (!CollectionUtils.isEmpty(productManageDTO.getColors())) {
            for (int i = 0; i < productManageDTO.getColors().size(); i++) {
                ProductManageDTO.ColorInfo colorInfo = productManageDTO.getColors().get(i);

                ProductSpecColor color = new ProductSpecColor();
                color.setProductId(product.getProductId());
                color.setColorName(colorInfo.getColorName());
                color.setImage(colorInfo.getImage());
                color.setSort(colorInfo.getSort() != null ? colorInfo.getSort() : 0);
                color.setCreateTime(LocalDateTime.now());

                productSpecColorService.save(color);
                colorIndexToId.put(i, color.getColorId());
            }
        }

        if (!CollectionUtils.isEmpty(productManageDTO.getSizes())) {
            for (int i = 0; i < productManageDTO.getSizes().size(); i++) {

                ProductManageDTO.SizeInfo sizeInfo = productManageDTO.getSizes().get(i);
                ProductSpecSize size = new ProductSpecSize();
                size.setProductId(product.getProductId());
                size.setSizeName(sizeInfo.getSizeName());
                size.setSort(sizeInfo.getSort() != null ? sizeInfo.getSort() : 0);
                size.setCreateTime(LocalDateTime.now());

                productSpecSizeService.save(size);
                sizeIndexToId.put(i, size.getSizeId());
            }
        }

        // 保存SKU信息（前端传索引：specColor/specSize）
        if (!CollectionUtils.isEmpty(productManageDTO.getSkus())) {
            for (ProductManageDTO.SkuInfo skuInfo : productManageDTO.getSkus()) {
                ProductSku sku = new ProductSku();
                sku.setProductId(product.getProductId());
                
                // 将索引映射为真实颜色ID/尺码ID
                if (skuInfo.getSpecColor() != null && skuInfo.getSpecSize() != null) {
                    Integer colorId = colorIndexToId.get(skuInfo.getSpecColor());
                    Integer sizeId = sizeIndexToId.get(skuInfo.getSpecSize());
                    if (colorId != null && sizeId != null) {
                        sku.setSpecColor(colorId);
                        sku.setSpecSize(sizeId);
                    }
                }

                sku.setPrice(skuInfo.getPrice());
                sku.setStock(skuInfo.getStock());
                sku.setSkuCode(skuInfo.getSkuCode());

                sku.setStatus(1); // 默认启用
                sku.setCreateTime(LocalDateTime.now());
                sku.setUpdateTime(LocalDateTime.now());

                productSkuService.save(sku);
            }
        }

        return Result.success(null, "商品添加成功");
    }

    /**
     * 修改商品（包括颜色、尺寸和SKU）
     *
     * @param productManageDTO 商品管理DTO
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result updateProduct(ProductManageDTO productManageDTO) {
        // 检查商品是否存在
        Product product = this.getById(productManageDTO.getProductId());
        if (product == null) {
            return Result.error("商品不存在");
        }

        // 更新商品基本信息
        product.setProductName(productManageDTO.getProductName());
        product.setCategoryId(productManageDTO.getCategoryId());
        product.setDefaultPrice(productManageDTO.getDefaultPrice());
        product.setMainImage(productManageDTO.getMainImage());
        product.setSubImages(productManageDTO.getSubImages());
        product.setDetail(productManageDTO.getDetail());
        product.setUpdateTime(LocalDateTime.now());

        this.updateById(product);

        // 删除该商品关联的颜色和尺码
        LambdaQueryWrapper<ProductSpecColor> colorWrapper = new LambdaQueryWrapper<>();
        colorWrapper.eq(ProductSpecColor::getProductId, product.getProductId());
        productSpecColorService.remove(colorWrapper);

        LambdaQueryWrapper<ProductSpecSize> sizeWrapper = new LambdaQueryWrapper<>();
        sizeWrapper.eq(ProductSpecSize::getProductId, product.getProductId());
        productSpecSizeService.remove(sizeWrapper);

        // 删除商品的所有SKU
        LambdaQueryWrapper<ProductSku> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(ProductSku::getProductId, product.getProductId());
        productSkuService.remove(skuWrapper);

        // 重新建立索引→颜色ID/尺码ID 映射
        Map<Integer, Integer> colorIndexToId = new java.util.HashMap<>();
        Map<Integer, Integer> sizeIndexToId = new java.util.HashMap<>();

        if (!CollectionUtils.isEmpty(productManageDTO.getColors())) {
            for (int i = 0; i < productManageDTO.getColors().size(); i++) {
                ProductManageDTO.ColorInfo colorInfo = productManageDTO.getColors().get(i);

                ProductSpecColor color = new ProductSpecColor();
                color.setProductId(product.getProductId());
                color.setColorName(colorInfo.getColorName());
                color.setImage(colorInfo.getImage());
                color.setSort(colorInfo.getSort() != null ? colorInfo.getSort() : 0);
                color.setCreateTime(LocalDateTime.now());

                productSpecColorService.save(color);
                colorIndexToId.put(i, color.getColorId());
            }
        }

        if (!CollectionUtils.isEmpty(productManageDTO.getSizes())) {
            for (int i = 0; i < productManageDTO.getSizes().size(); i++) {

                ProductManageDTO.SizeInfo sizeInfo = productManageDTO.getSizes().get(i);
                ProductSpecSize size = new ProductSpecSize();
                size.setProductId(product.getProductId());
                size.setSizeName(sizeInfo.getSizeName());
                size.setSort(sizeInfo.getSort() != null ? sizeInfo.getSort() : 0);
                size.setCreateTime(LocalDateTime.now());

                productSpecSizeService.save(size);
                sizeIndexToId.put(i, size.getSizeId());
            }
        }

        // 重新创建SKU信息（前端传索引：specColor/specSize）
        if (!CollectionUtils.isEmpty(productManageDTO.getSkus())) {
            for (ProductManageDTO.SkuInfo skuInfo : productManageDTO.getSkus()) {
                ProductSku sku = new ProductSku();
                sku.setProductId(product.getProductId());
                
                // 将索引映射为真实颜色ID/尺码ID
                if (skuInfo.getSpecColor() != null && skuInfo.getSpecSize() != null) {
                    Integer colorId = colorIndexToId.get(skuInfo.getSpecColor());
                    Integer sizeId = sizeIndexToId.get(skuInfo.getSpecSize());
                    if (colorId != null && sizeId != null) {
                        sku.setSpecColor(colorId);
                        sku.setSpecSize(sizeId);
                    }
                }

                sku.setPrice(skuInfo.getPrice());
                sku.setStock(skuInfo.getStock());
                sku.setSkuCode(skuInfo.getSkuCode());

                sku.setStatus(1); // 默认启用
                sku.setCreateTime(LocalDateTime.now());
                sku.setUpdateTime(LocalDateTime.now());

                productSkuService.save(sku);
            }
        }
        
        return Result.success(null, "商品修改成功");
    }

    /**
     * 设置商品上架状态
     * @param productId 商品id
     * @param status 上架状态（1-上架，0-下架）
     * @return 操作结果
     */
    @Override
    public Result productBan(Integer productId, Integer status) {
        if (IntegerUtils.isEmptyOrZero(productId)){
            return Result.error("商品id值错误");
        }
        if (status !=0 && status!=1){
            return Result.error("上架状态值错误（1-上架，0-下架）");
        }
        Product product=new Product();
        product.setProductId(productId);
        product.setStatus(status);
        boolean result=updateById(product);
        if (result) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 批量上下架
     * @param productIds 商品id数组
     * @param status 上架状态（1-上架，0-下架）
     * @return 操作结果
     */
    @Override
    @Transactional
    public Result productsBan(List<Integer> productIds, Integer status) {
        if (CollectionUtils.isEmpty(productIds)) {
            return Result.error("商品ID列表不能为空");
        }
        
        if (status != 0 && status != 1) {
            return Result.error("上架状态值错误（1-上架，0-下架）");
        }
        
        // 检查是否有无效的商品ID
        for (Integer productId : productIds) {
            if (IntegerUtils.isEmptyOrZero(productId)) {
                return Result.error("商品ID值错误");
            }
        }
        
        // 批量更新商品状态
        List<Product> products = productIds.stream().map(productId -> {
            Product product = new Product();
            product.setProductId(productId);
            product.setStatus(status);
            product.setUpdateTime(LocalDateTime.now());
            return product;
        }).collect(Collectors.toList());
        
        boolean result = updateBatchById(products);
        if (result) {
            return Result.success("批量操作成功");
        } else {
            return Result.error("批量操作失败");
        }
    }
}